//
//  InstrumentsSelectorViewController.swift
//  Duyiguqin
//
//  Created by 张昭 on 2024/8/11.
//

import UIKit

class InstrumentsSelectorViewController: UIViewController {
    
    var onSubmit: ((Instrument) -> Void)?
    
    private let instruments: [Instrument]
    private var selectedInstrument: Instrument

    init(instruments v1: [Instrument], selected v2: Instrument) {
        instruments = v1
        selectedInstrument = v2
        super.init(nibName: nil, bundle: nil)
        self.transitioningDelegate = self
        self.modalPresentationStyle = .overFullScreen
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        addContentView()
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touchPoint = touches.first?.location(in: view) else { return }
        guard !boardView.frame.contains(touchPoint) else { return }
        dismiss(animated: true)
    }
    
    override func viewSafeAreaInsetsDidChange() {
        super.viewSafeAreaInsetsDidChange()
        contentView.snp.updateConstraints { make in
            make.bottom.equalTo(-view.safeAreaInsets.bottom)
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        if boardView.layer.mask == nil {
            boardView.roundCorners(corners: [.topLeft, .topRight], radius: 5)
        }
    }
    
    lazy var contentView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor.white
        return v
    }()
    
    private lazy var boardView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor.white
        return v
    }()

    private lazy var cancelButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setTitle("取消", for: .normal)
        v.setTitleColor(UIColor.black, for: .normal)
        v.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: .regular)
        v.addTarget(self, action: #selector(onClickCloseButton(_:)), for: .touchUpInside)
        return v
    }()
    
    private lazy var okButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setTitle("确定", for: .normal)
        v.setTitleColor(UIColor(0xD3C390), for: .normal)
        v.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: .regular)
        v.addTarget(self, action: #selector(onClickOKButton(_:)), for: .touchUpInside)
        return v
    }()
    
    private let bgView = UIView()
}

extension InstrumentsSelectorViewController {
    
    private func addContentView() {
        view.backgroundColor = .clear
        view.addSubview(boardView)
        boardView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
        }
        
        boardView.addSubview(contentView)
        contentView.snp.makeConstraints { make in
            make.top.left.right.equalTo(0)
            make.bottom.equalTo(-view.safeAreaInsets.bottom)
        }
        
        contentView.addSubview(cancelButton)
        cancelButton.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.height.equalTo(40)
            make.top.equalTo(10)
        }
        
        contentView.addSubview(okButton)
        okButton.snp.makeConstraints { make in
            make.right.equalTo(-15)
            make.height.equalTo(40)
            make.centerY.equalTo(cancelButton)
        }

        contentView.addSubview(bgView)
        let space: CGFloat = 15
        let numPerRow = 4
        let itemWidth: CGFloat = (UIScreen.main.bounds.size.width - space) / CGFloat(numPerRow) - space
        let itemHeight: CGFloat = 30
        let rows = Int(ceil(Double(instruments.count) / Double(numPerRow)))
        var k = 0
        var maxY: CGFloat = 0
        for i in 0..<rows {
            for j in 0..<numPerRow {
                guard k < instruments.count else { break }
                let ins = instruments[k]
                let isSelected = ins.id == selectedInstrument.id
                k += 1
                let btn = UIButton(type: .custom)
                btn.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
                btn.setTitle(ins.name, for: .normal)
                btn.setTitleColor(UIColor(0x0F0F0F), for: .normal)
                btn.setTitleColor(UIColor.white, for: .selected)
                btn.setBackgroundImage(UIImage.color(UIColor(0xD3C390)), for: .selected)
                btn.setBackgroundImage(UIImage.color(UIColor(0xF2F2F2)), for: .normal)
                btn.layer.cornerRadius = 12
                btn.layer.masksToBounds = true
                btn.addTarget(self, action: #selector(onClickItemButton(_:)), for: .touchUpInside)
                btn.isSelected = isSelected
                bgView.addSubview(btn)
                btn.frame = CGRect(x: space + CGFloat(j) * (itemWidth + space), y: CGFloat(i) * 65, width: itemWidth, height: itemHeight)
                maxY = btn.frame.maxY
            }
        }
        bgView.snp.makeConstraints { make in
            make.top.equalTo(cancelButton.snp.bottom).offset(20)
            make.left.right.equalTo(0)
            make.height.equalTo(maxY)
            make.bottom.equalTo(-20)
        }
    }
    
    @objc func onClickCloseButton(_ sender: UIButton) {
        view.endEditing(true)
        dismiss(animated: true, completion: nil)
    }
    
    @objc func onClickOKButton(_ sender: UIButton) {
        view.endEditing(true)
        let ins = selectedInstrument
        dismiss(animated: true) { [weak self] in
            self?.onSubmit?(ins)
        }
    }
    
    @objc private func onClickItemButton(_ sender: UIButton) {
        guard let btns = bgView.subviews as? [UIButton] else { return }
        for i in 0..<btns.count {
            let btn = btns[i]
            if btn == sender {
                btn.isSelected = true
                selectedInstrument = instruments[i]
            } else {
                btn.isSelected = false
            }
        }
    }
}

// MARK: - UIViewControllerTransitioningDelegate
extension InstrumentsSelectorViewController: UIViewControllerTransitioningDelegate {
    
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return self
    }
    
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return self
    }
}

// MARK: - UIViewControllerAnimatedTransitioning
extension InstrumentsSelectorViewController: UIViewControllerAnimatedTransitioning {
    
    private var transitionDuration: TimeInterval {
        return 0.15
    }
    
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return transitionDuration
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        if isBeingPresented {
            transitionContext.containerView.addSubview(view)
            boardView.transform = CGAffineTransform(translationX: 0, y: 300)
            self.view.backgroundColor = UIColor(0x35373F, alpha: 0)
            UIView.animate(withDuration: transitionDuration) {
                self.boardView.transform = CGAffineTransform.identity
                self.view.backgroundColor = UIColor(0x35373F, alpha: 0.8)
            } completion: { _ in
                transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            }
        } else {
            UIView.animate(withDuration: transitionDuration) {
                self.boardView.transform = CGAffineTransform(translationX: 0, y: self.boardView.frame.size.height)
                self.view.backgroundColor = UIColor(0x35373F, alpha: 0)
            } completion: { _ in
                transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            }
        }
    }
}
